from urlparse import urlparse
import urllib2, urllib
import sys

from auth import *
from utils import *
from const import *
from parser import *
from display import *

class Digu:
    '''core function'''
    
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.authhandle = Auth()
        self.authheader = self.authhandle.b64_string(self.username, self.password)
        self.current_list= []
        self.errorcode = ''

    def timeline(self, url, user = None, digu_id = None):
        '''get timeline'''
    
        
        url_value = {}
        url_value['userIdOrName'] = user
        url_value['id'] = digu_id

        url_value = dict((k, v) for k, v in url_value.iteritems() if v)
    
        if url_value:
            url_value = urllib.urlencode(url_value)
            url = url + '?' + url_value
        req = urllib2.Request(url)
        req.add_header("Authorization", self.authheader)
        try:
            handle = urllib2.urlopen(req)
        except IOError, e:
            self.errorcode = e.read()
            return None
        else:
            return handle.read()

    def update(self, msg, digu_id=None):
        
        req = urllib2.Request('http://api.minicloud.com.cn/statuses/update.xml')
        
        req.add_header("Authorization", self.authheader)
        form_fields = {
                        'content': msg,
                        'source': 'diceboy',
                        'digu_id': digu_id,
                        }
        
        try:
            handle = urllib2.urlopen(req, urllib.urlencode(form_fields))
        except IOError, e:
            self.errorcode = e.read()
            return None
        else:
            return True
    
